/*
 * 物资管理视图
 * @Author: ljb
 * @Date: 2018-07-12 09:59:32
 * @Last Modified by: ljb
 * @Last Modified time: 2018-09-04 10:57:22
 */
<style lang="less" rel="stylesheet/less" type="text/less">
    .v-admin-material-views {
        padding: 20px;
    }
</style>
<template>
	<div class="v-admin-material-views">
		<Tabs
			type="card"
			@on-click="changeTab">

			<TabPane
				:label="$t('common.create')"
				name="new">
				<material-create
					ref="create"
					:materials="materials_options"
					:loading="table_loading"
					@add="addMaterial"
					@post="postData"/>
			</TabPane>

			<TabPane
				:label="$t('common.check')"
				name="watch">

				<searchForm @search="confirmSearch"/>

				<material-index
					:loading="table_loading"
					:materials="materials.data"
					@sell="showModal"
					@sort="confirmSearch"/>
				<br>

				<!-- 分页组件 -->
				<Row
					type="flex"
					justify="center">
					<Page
						:total="materials.total"
						:current="materials.current_page"
						:page-size="query_info.per_page"
						placement="top"
						show-sizer
						show-total
						@on-change="pageChange"
						@on-page-size-change="perPageChange"/>
				</Row>

			</TabPane>

			<TabPane
				:label="$t('supplies_management.sold_list')"
				name="sold">

				<soldSearchForm
					:customers="customers"
					@search="confirmSearch"/>

				<material-sold-index
					:loading="sold_table_loading"
					:materials="material_sales.data"
					@sort="confirmSearch"/>
				<br>

				<!-- 分页组件 -->
				<Row
					type="flex"
					justify="center">
					<Page
						:total="material_sales.total"
						:current="material_sales.current_page"
						:page-size="query_info.per_page"
						placement="top"
						show-sizer
						show-total
						@on-change="pageChange"
						@on-page-size-change="perPageChange"/>
				</Row>

			</TabPane>

		</Tabs>

		<Modal
			v-model="show_modal"
			:title="$t('supplies_management.sell')"
			class-name="vertical-middle-modal"
			@on-cancel="cancelModal">

			<!-- 出售物资 -->
			<material-edit
				ref="sell_edit"
				:material-detail="material_detail"
				:customers="customers"
				@update="sellMaterial"/>

			<div slot="footer"/>

		</Modal>

	</div>
</template>

<script>

import API_LIST from 'src/API_LIST';
import { mapMutations } from 'vuex';
import qs from 'qs';
import { deleteEmptyValue } from 'src/utils/utils';

import materialCreate from './create';
import materialEdit from './edit';
import materialIndex from './index';
import materialSoldIndex from './sold_index';
import searchForm from './search-form';
import soldSearchForm from './sold-search-form';

export default {

	name: 'SuppliesViews',

	components: {
		materialCreate,

		materialEdit,

		materialIndex,

		materialSoldIndex,

		searchForm,

		soldSearchForm,
	},
	data() {
		return {
			table_loading: false, // 物资表格更新时的loading

			sold_table_loading: false,	// 出售记录表格更新时的loading

			show_modal: false, // 弹框的控制

			material_detail: {},		// 当前操作的数据

			current_tab: '',	// 当前的tab的name值

			customers: [], // 客户信息

			materials_options: [], // 已有物资列表选项

			materials: {}, // 物资列表信息

			material_sales: {}, // 出售物资列表

			query_info: {

				page: 1,

				per_page: 10,

				name: '',

				buyer: '',

				manufacturer: '',

				customer_id: '',

				operator: '',

				time_range: [],

				order_by: [],

			}, // 搜索参数

			search_info: {

				page: 1,

			}, // 页码数
		};
	},
	mounted() {
		this.fetchCustomer();
	},
	methods: {

		...mapMutations('spinShow', [
			'showSpin',
			'closeSpin',
		]),

		/**
		 * 关闭弹框的回调
		 * @return {undefined}
		 */
		cancelModal() {
			this.$refs.sell_edit.handleReset('formValidate');
		},

		/**
		 * 重置搜索参数
		 * @return {undefined}
		 */
		resetSearchParam() {
			this.query_info = {

				page: 1,

				per_page: 10,

				name: '',

				buyer: '',

				manufacturer: '',

				customer_id: '',

				operator: '',

				time_range: [],

				order_by: [],

			};

			this.search_info = {

				page: 1,

			};
		},

		/**
         * 切换tab
         * @param  {string} tab_name {tab的name}
         * @return {undefined}
         */
		changeTab(tab_name) {
			this.resetSearchParam();

			this.current_tab = tab_name;
			if (tab_name === 'watch') {
				this.fetchMaterialList(this.query_info);

				this.$refs.create.handleReset('formValidate');
			} else if (tab_name === 'sold') {
				this.fetchSoldList(this.query_info);

				this.$refs.create.handleReset('formValidate');
			} else {
				this.materials.data = [];
			}
		},

		/**
         * 页码改变
         * @param  {string} pageNumber {当前页码}
         * @return {undefined}
         */
		pageChange(pageNumber) {
			this.search_info.page = pageNumber;

			this.search_info.per_page = this.query_info.per_page;

			this.fetchMaterialList(this.search_info);
		},

		/**
         * 每页显示数改变
         * @param  {string} per_page {当前每页显示数}
         * @return {undefined}
         */
		perPageChange(per_page) {
			this.search_info.per_page = per_page;

			this.query_info.per_page = per_page;

			this.fetchMaterialList(this.query_info);
		},

		/**
         * 确认搜索
         * @param  {Object} param {搜索的参数对象}
         * @return {undefined}
         */
		confirmSearch({
			name, buyer, manufacturer, time_range, order_by, sort, customer_id, operator,
		}) {
			this.query_info.name = name || '';
			this.query_info.buyer = buyer || '';
			this.query_info.manufacturer = manufacturer || '';
			this.query_info.time_range = time_range || [];
			this.query_info.customer_id = customer_id || '';
			this.query_info.operator = operator || '';
			// 排序
			this.query_info.order_by = order_by && sort ? [{ order_by, sort }] : [];

			this.search_info = JSON.parse(JSON.stringify(this.query_info));

			switch (this.current_tab) {
			case 'watch':
				this.fetchMaterialList(this.query_info);

				break;
			case 'sold':
				this.fetchSoldList(this.query_info);

				break;

			default:
				break;
			}
		},

		/**
		 * 显示弹框
		 * @param  {Object}} row {当前行数据}
		 * @return {undefined}
		 */
		showModal(row) {
			this.material_detail = row;

			this.show_modal = true;
		},

		/**
		 * 提交出售物资
		 * @param  {Object} param {post给后端的数据对象}
		 * @return {undefined}
		 */
		sellMaterial(param) {
			this.showSpin(this.$t('common.please_wait'));

			this.$http.post(`${API_LIST.ADMIN_MATERIAL}/${this.material_detail.id}`, param)
				.then(({ data }) => {
					if (parseInt(data.code, 10) !== 0) throw new Error(data.error);

					this.$Message.success(this.$t('common.operate_success'));

					this.show_modal = false;

					this.fetchMaterialList(this.search_info);
				})
				.catch((err) => {
					this.$Message.error(err.message || err.statusText);
				})
				.then(this.closeSpin);
		},

		/**
		 * 从已有的物资增加物资
		 * @param  {Object} param {post给后端的数据对象}
		 * @return {undefined}
		 */
		addMaterial(param) {
			this.showSpin(this.$t('common.please_wait'));

			this.$http.post(API_LIST.ADMIN_MATERIAL_ADD, param)
				.then(({ data }) => {
					if (parseInt(data.code, 10) !== 0) throw new Error(data.error);

					this.$Message.success(this.$t('common.create_success'));

					this.$refs.create.handleReset('oldFormValidate');
				})
				.catch((err) => {
					this.$Message.error(err.message || err.statusText);
				})
				.then(this.closeSpin);
		},

		/**
         * 新增物资的post数据
		 * @param  {Object} param {post给后端的数据对象}
         * @return {undefined}
         */
		postData(param) {
			this.showSpin(this.$t('common.please_wait'));

			this.$http.post(API_LIST.ADMIN_MATERIAL, param)
				.then(({ data }) => {
					if (parseInt(data.code, 10) !== 0) throw new Error(data.error);

					this.$Message.success(this.$t('common.create_success'));

					this.$refs.create.handleReset('formValidate');
				})
				.catch((err) => {
					this.$Message.error(err.message || err.statusText);
				})
				.then(this.closeSpin);
		},

		/**
         * 获取出售记录列表
         * @param  {Object} param {搜索列表的参数}
         * @return {undefined}
         */
		fetchSoldList(param) {
			this.sold_table_loading = true;

			const query_str = qs.stringify(deleteEmptyValue(param));

			this.$http.get(`${API_LIST.ADMIN_MATERIAL_SOLD}?${query_str}`)
				.then(({ data }) => {
					if (parseInt(data.code, 10) !== 0) throw new Error(data.error);
					this.material_sales = data.material_sales;
				})
				.catch((err) => {
					this.$Message.error(err.message || err.statusText);
				})
				.then(() => { this.sold_table_loading = false; });
		},

		/**
         * 获取库存物资列表
         * @param  {Object} param {搜索列表的参数}
         * @return {undefined}
         */
		fetchMaterialList(param) {
			this.table_loading = true;

			const query_str = qs.stringify(deleteEmptyValue(param));

			this.$http.get(`${API_LIST.ADMIN_MATERIAL}?${query_str}`)

				.then(({ data }) => {
					if (parseInt(data.code, 10) !== 0) throw new Error(data.error);
					this.materials = data.material_purchases;
				})

				.catch((err) => {
					this.$Message.error(err.message || err.statusText);
				})

				.then(() => { this.table_loading = false; });
		},

		/**
		 * 获取已有物资/搜索框客户信息
		 * @return {undefined}
		 */
		fetchCustomer() {
			this.showSpin(this.$t('common.please_wait'));

			this.$http.get(`${API_LIST.ADMIN_MATERIAL}/create`)
				.then(({ data }) => {
					if (parseInt(data.code, 10) !== 0) throw new Error(data.error);
					this.customers = data.customers;
					this.materials_options = data.materials;
				})
				.catch((err) => {
					this.$Message.error(err.message || err.statusText);
				})
				.then(this.closeSpin);
		},
	},
};
</script>

